import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores/user';

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/Register.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('../layouts/BasicLayout.vue'),
      children: [
        {
          path: '',
          name: 'home-index',
          component: () => import('../views/Home.vue')
        }
      ]
    },
    {
      path: '/course/:id',
      name: 'course-detail',
      component: () => import('../views/CourseDetail.vue')
    },
    {
      path: '/teachers',
      name: 'teachers',
      component: () => import('../views/Teachers.vue')
    },
    {
      path: '/search',
      name: 'search',
      component: () => import('../views/Search.vue')
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('../views/Profile.vue')
    },
    // 添加404路由
    {
      path: '/:pathMatch(.*)*',
      redirect: '/home'
    }
  ]
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  const isAuthenticated = userStore.token;

  // 不需要验证的路由直接通过
  if (to.meta.requiresAuth === false) {
    next();
    return;
  }

  // 需要验证且未登录，跳转到登录页
  if (!isAuthenticated && to.path !== '/login') {
    next('/login');
    return;
  }

  next();
});

export default router;
